package com.itheima.springboottest.controller;

import com.itheima.springboottest.mapper.UserMapper;
import com.itheima.springboottest.pojo.Result;
import com.itheima.springboottest.pojo.User;
import com.itheima.springboottest.service.UserServive;
import com.itheima.springboottest.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@Validated
public class UserController {

    @Autowired
    public UserServive userServive;
    @Autowired
    private UserMapper userMapper;

    //根据id找到用户详情
    @RequestMapping("/findById")
    public User findById(Integer id) {
        return  userServive.findById(id);
    }

    //注册用户
    @PostMapping("/register")
    public Result registerUser(@Pattern(regexp = "^\\S{5,16}$") String username,  @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userServive.findByUserName(username);
        if(user == null){
            //注册
            userServive.registerUser(username,password);
            return Result.success();
        }else {
            //当前用户已被注册
            return  Result.success("当前用户已被注册");
        }
    }

    //用户登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userServive.findByUserName(username);
        if(user == null){
            //注册
            return  Result.success("当前用户还未被注册");
        }else {
            //登录
             String token =  userServive.login(username,password);
            return  Result.success(token);
        }
    }


    //查询用户信息
    @GetMapping("/userInfo")
    public Result userInfo() {
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = map.get("username").toString();
        User user = userServive.findByUserName(username);
        return Result.success(user);
    }

    //更新用户基本信息
    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());//重新设置当前更新时间
        userMapper.update(user);
        return Result.success();
    }

}
